#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time    : 2024/2/21 15:26
# @Author  : jiangwei
# @Site    : 
# @File    : temu_shop_new_life.py
# @Software: PyCharm
import sys
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)

# temu 2024年2月新需求
# 商品管理 - 上新生命周期管理 - 全部
# 商品管理 - 图片更新任务 - 待更新&更新中&待发布&待确认&已完成

import requests
import json
import time
from datetime import datetime
import math
from utils.trans_date import trans_time_stamp_to_str
from utils.oversea_proxy import read_cookie


def map_sku_status(status_code):
    """
    映射 SKC属性
     # SKC属性状态
    #              14【未发布】待修改
    #              15 【未发布】修改完成
    #              [1，16] 【未发布】未发布
    # ——-------------------------------------
    #              3 【待寄样】待寄样
    #              4 【待寄样】寄样中
    # ——-------------------------------------
    #              5 【审版中】平台审版中
    #              6 【审版中】审版不合格
    # ——-------------------------------------
    #              7 【价格申报中】价格申报中
    #              9 【价格申报中】价格已作废
    # ——-------------------------------------
    #              10 【待创建首单】
    # ——-------------------------------------
    #              11 【已创建首单】
    # ——-------------------------------------
    #              12 【已发布到站点】
    # ——-------------------------------------
    #              13  【已下架/终止】 已下架
    #              17  【已下架/终止】已终止

    :return:
    """
    skc_status_dict = {
        1: "未发布",
        3: "待寄样",
        4: "寄样中",
        5: "平台审版中",
        6: "审版不合格",
        7: "价格申报中",
        9: "价格已作废",
        10: "待创建首单",
        11: "已创建首单",
        12: "已发布到站点",
        13: "已下架",
        17: "已终止",

    }

    return skc_status_dict.get(status_code)


def map_price_status(status):
    """
    映射价格状态   NULL代表无内容 0代表价格申报中    2代表已生效   1待卖家确认   3 代表已作废
    :param status:
    :return:
    """
    price_status_dict = {
        0: "价格申报中",
        1: "待卖家确认",
        2: "已生效",
        3: "已作废",
    }

    return price_status_dict.get(status, None)


def format_property(productPropertyList):
    """
    格式化 属性信息
    :param productPropertyList:
    :return:
    """
    skcProperty = ""
    for property in productPropertyList:
        skcProperty += property["name"] + ":" + property["value"] + "; "

    return skcProperty[:-2]


def parse_xmen(msg):
    """
    解析数据 #  SKC	SPU	货号	状态		标题	类目	规格	申报价格	申报价格状态	创建时间	可寄样开始时间	审版完成时间	价格确认时间	备货单首单创建时间	加入站点时间
    :param msg:
    :return:
    """
    sku_list = []
    supplierId = msg.get("supplierId")
    spu = msg.get("productId")  # SPU
    productName = msg.get("productName")  # 标题
    fullCategoryName = ",".join(msg.get("fullCategoryName", []))  # 类目
    productPropertyList = msg.get("productPropertyList")  # 属性
    property = format_property(productPropertyList) if productPropertyList else None
    skc_dict = msg.get("skcList")[0]
    skc = skc_dict["skcId"]  # SKC
    selectStatus = skc_dict["selectStatus"]  # 状态
    skuStatus = map_sku_status(status_code=selectStatus)
    skuList = skc_dict["skuList"]
    statusTime = skc_dict.get("statusTime")
    # print(statusTime)
    # 创建时间	可寄样开始时间	审版完成时间	价格确认时间	备货单首单创建时间	加入站点时间
    createdTime = trans_time_stamp_to_str(int(statusTime["createdTime"] / 1000)) if statusTime.get(
        "createdTime") else None  # 创建时间
    selectedTime = trans_time_stamp_to_str(int(statusTime["selectedTime"] / 1000)) if statusTime.get(
        "selectedTime") else None  # 可寄样开始时间
    samplePostTime = trans_time_stamp_to_str(int(statusTime["samplePostTime"] / 1000)) if statusTime.get(
        "samplePostTime") else None
    qcCompletedTime = trans_time_stamp_to_str(int(statusTime["qcCompletedTime"] / 1000)) if statusTime.get(
        "qcCompletedTime") else None  # 审版完成时间
    priceVerificationTime = trans_time_stamp_to_str(int(statusTime["priceVerificationTime"] / 1000)) if statusTime.get(
        "priceVerificationTime") else None  # 价格确认时间
    firstPurchaseTime = trans_time_stamp_to_str(int(statusTime["firstPurchaseTime"] / 1000)) if statusTime.get(
        "firstPurchaseTime") else None  # 备货单首单创建时间
    addedToSiteTime = trans_time_stamp_to_str(int(statusTime["addedToSiteTime"] / 1000)) if statusTime.get(
        "addedToSiteTime") else None  # 加入站点时间
    unPublishedTime = trans_time_stamp_to_str(int(statusTime["unPublishedTime"] / 1000)) if statusTime.get(
        "unPublishedTime") else None  # 下架时间
    samplePostingFinishedTime = trans_time_stamp_to_str(
        int(statusTime["samplePostingFinishedTime"] / 1000)) if statusTime.get("samplePostingFinishedTime") else None
    terminatedTime = trans_time_stamp_to_str(int(statusTime["terminatedTime"] / 1000)) if statusTime.get(
        "terminatedTime") else None
    # print(samplePostTime,  samplePostingFinishedTime, terminatedTime)

    for sku in skuList:
        sku_detail = {}
        goodsSkuId = sku["goodsSkuId"]
        extCode = sku["extCode"]  # 货号
        supplierPrice = sku["supplierPrice"]  # 申报价格
        priceReviewStatus = sku["priceReviewStatus"]
        supplierPriceReviewInfoList = skc_dict["supplierPriceReviewInfoList"]
        priceStatus = supplierPriceReviewInfoList[0]["status"]  # NULL代表无内容 0代表价格申报中    2代表已生效   1待卖家确认   3 代表已作废
        priceStatusStr = map_price_status(priceStatus)
        skuProductPropertyList = sku["productPropertyList"]
        skuProperty = skuProductPropertyList[0]["value"] if skuProductPropertyList else None
        #  SKC	SPU	货号	状态		标题	类目	规格	申报价格	申报价格状态	创建时间	可寄样开始时间	审版完成时间	价格确认时间	备货单首单创建时间	加入站点时间
        sku_detail.update({
            "date": datetime.now().strftime('%Y-%m-%d %H:%M:%S').split(" ")[0],
            "platform": "temu_seller_xmen",
            "store_code": supplierId,  # 卖家id
            "spu": spu,  # spu-id
            "product_name": productName,  # 标题
            "full_category_name": fullCategoryName,  # 类目
            "property": property,  # 商品属性
            "skc": skc,  # skc-id
            "select_status": selectStatus,  # SKC属性 之 状态 API给的原始字段内容为 数字
            "sku_status": skuStatus,  # SKC属性 之 状态  映射为中文
            "goods_sku_id": goodsSkuId,  # sku-id
            "sku_property": skuProperty,  # SKU属性集
            "ext_code": extCode,  # 货号
            "supplier_price": supplierPrice.replace("元", "") if supplierPrice else None,  # 申报价格 要数字类型
            "supplier_price_str": supplierPrice,
            "price_status": priceStatus,  # 申报价格状态 API给的原始字段内容为 数字
            "price_status_str": priceStatusStr,  # 申报价格状态  映射为中文
            "created_time": createdTime,  # 创建时间
            "selected_time": selectedTime,  # 可寄样开始时间
            "sample_post_time": samplePostTime,  # ???  未知
            "qc_completed_time": qcCompletedTime,  # 审版完成时间
            "price_verification_time": priceVerificationTime,  # 价格确认时间
            "first_purchase_time": firstPurchaseTime,  # 备货单首单创建时间
            "added_to_site_time": addedToSiteTime,  # 加入站点时间
            "unpublished_time": unPublishedTime,  # 下架时间
            "sample_posting_finished_time": samplePostingFinishedTime,  # ???   未知
            "terminated_time": terminatedTime,  # ???   未知

        })

        # print(sku_detail)
        # print(skuProductPropertyList)
        sku_list.append(sku_detail)

    return sku_list


def record_count(mall_id, count, platform, sql_obj=None):
    """
    记录数据量
    :param mall_id:
    :param count:
    :param platform:
    :param sql_obj:
    :return:
    """
    if sql_obj:
        data = {
            "date": datetime.now().strftime('%Y-%m-%d %H:%M:%S').split(" ")[0],
            "platform": platform,
            "store_code": mall_id,
            "count": count
        }
        sql_obj.record_goods_count(data=data)

    return True


def temu_xmen_api(page=1, sku_all=[], mall_id="4594954014482", sql_obj=None):
    """
    temu 卖家端  # 商品管理 - 上新生命周期管理 - 全部
    字段：SKC	SPU	货号	状态	主体材料	适用年龄段	标题	类目	规格	申报价格	申报价格状态	创建时间	可寄样开始时间	审版完成时间	价格确认时间	备货单首单创建时间	加入站点时间
    :return:
    """
    cookies = read_cookie(platform_name="temu_seller")
    print(cookies)
    if not cookies:
        print("需要登录")
        return
    cookies.update({
        "mallid": mall_id
    })

    headers = {
        "authority": "agentseller.temu.com",
        "accept": "*/*",
        "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
        "cache-control": "no-cache",
        "content-type": "application/json",
        "mallid": "4594954014482",
        "origin": "https://agentseller.temu.com",
        "pragma": "no-cache",
        "referer": "https://agentseller.temu.com/newon/product-select",
        "sec-ch-ua": "\" Not A;Brand\";v=\"99\", \"Chromium\";v=\"100\", \"Microsoft Edge\";v=\"100\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "\"Windows\"",
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-origin",
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36 Edg/100.0.1185.36"
    }
    headers.update({
        "mallid": mall_id
    })

    json_data = {
        'pageSize': 100,
        'pageNum': page,
        'supplierTodoTypeList': [],
    }

    response = requests.post(
        # 'https://seller.kuajingmaihuo.com/marvel-supplier/api/xmen/select/search',
        # 20241227接口改版
        # "https://seller.kuajingmaihuo.com/marvel-mms/cn/api/kiana/xmen/select/searchForChainSupplier",
        # 2025.8.1接口改版
        "https://agentseller.temu.com/api/kiana/mms/robin/searchForChainSupplier",
        cookies=cookies,
        headers=headers,
        json=json_data,
    )
    result_json = response.json()
    print(result_json)
    if result_json.get("error_msg"):
        print(result_json)
        return False

    data_list = result_json.get("result").get("dataList")
    if not data_list:
        record_count(mall_id=mall_id, count=0, platform="temu_seller_xmen", sql_obj=sql_obj)
        return []

    total = result_json.get("result").get("total")
    page_all = math.ceil(total / json_data["pageSize"])
    record_count(mall_id=mall_id, count=total, platform="temu_seller_xmen", sql_obj=sql_obj)

    for i in range(len(data_list)):
        msg = data_list[i]
        # print(i, "----", msg)
        sku_list = parse_xmen(msg=msg)
        sku_all.extend(sku_list)
        # print("\n")
        # time.sleep(1)
    if page < page_all:
        page += 1
        return temu_xmen_api(page=page, sku_all=sku_all, mall_id=mall_id, sql_obj=sql_obj)
    else:
        print("sku 总量：{}".format(len(sku_all)))
        print("采集结束, 总共{}页".format(page_all))
        return sku_all


def map_picture_status(status):
    """
    映射状态信息
    :param status:
    :return:
    """
    picture_status_dict = {
        1: "待更新",
        2: "更新中",
        3: "待发布",
        4: "待确认",
        5: "已完成"
    }
    return picture_status_dict.get(status)


def temu_shop_picture_api(page=1, mall_id="4594954014482", sku_all=[], task_merged_status=1, sql_obj=None):
    """
    商品管理 - 图片更新任务 - 待更新&更新中&待发布&待确认&已完成
    字段：货品SKC	SPU	更新状态
    :return:
    """
    skcs = []
    cookies = read_cookie(platform_name="temu_seller")
    headers = {
        'authority': 'seller.kuajingmaihuo.com',
        'accept': '*/*',
        'accept-language': 'zh-CN,zh;q=0.9',
        # 'anti-content': '0aqWfac5rjQaF99xzhTxXJzxBZhxgpmtLzEyf2TddgTQat2XZZ_LT-SHrj_75FlZO62xups7wupvTWuSe805blflbhfMJByfhenovAWJKoY6XuQE8rbYiZjVHhQNf0VJo5o8gW4RRBve3Xg-ygiJJu6tLPbafw5pr94b3VbEAOVoe9f67DGFEzgj8nMyQBUbBlQBf_rM3Rm3XuYzil-2w-ft_7z-19tsewdc4q1Xtn9tW1_uSkoSnWAiLApeywBvEUPIhqddBIP5V22OFFuFay6etulf4U9zw9ztGytT1wW2fHHdcYgZxE55bIO4UP4qdI1EcjW91weB2wxx8tGKn0YMPjs_zPsR4ATXbbXUvxCxFSAcwMsiea0YkmpU3ZccaDAgYFOm3s_gTCHnD8r5vDi5vR-qEpeGWoTGnnO78cOs5cZDLcAiUDOvM5PY8qqCYcmO4JnDRKnALCDOGdjJp6FZcmn3wLM6oSG3ih0NjChsyzgWvSU7zbxv',
        'cache-control': 'max-age=0',
        'content-type': 'application/json',
        # 'cookie': 'api_uid=CmkArWXVpNMVmABXna3VAg==; _bee=vGKvwQzH4UuFTd8jtPkyEBazOnZQVamO; rckk=vGKvwQzH4UuFTd8jtPkyEBazOnZQVamO; ru2k=ff9edc7c-396a-4cc6-b25e-8ef18c45fca5; ru1k=9b87e0b2-bcd3-48b3-87fb-2cb4d810cb74; _a42=ff9edc7c-396a-4cc6-b25e-8ef18c45fca5; SUB_PASS_ID=eyJ0IjoiUjZKc0k5VWs3UTgyY3ZSRHdLUURITHcxL1hjLzJuUUNROXdNTml3WjE5b3ZyckxKbHJsWkxaM3IxOFV4Z2JhQyIsInYiOjEsInMiOjEwMDAwLCJ1IjoxMDIxNDU3NTY0NzE0MH0=; _f77=9b87e0b2-bcd3-48b3-87fb-2cb4d810cb74; _nano_fp=Xpmol0T8n0dYnqT8n9_Yscv3xJIiHGeuDSAgO6Qr; api_uid=CmgYBWXVpJyKdABZn8gPAg==; _bee=vGKvwQzH4UuFTd8jtPkyEBazOnZQVamO; rckk=vGKvwQzH4UuFTd8jtPkyEBazOnZQVamO; _f77=9b87e0b2-bcd3-48b3-87fb-2cb4d810cb74; _a42=ff9edc7c-396a-4cc6-b25e-8ef18c45fca5; ru1k=9b87e0b2-bcd3-48b3-87fb-2cb4d810cb74; ru2k=ff9edc7c-396a-4cc6-b25e-8ef18c45fca5',
        'mallid': '4594954014482',
        'origin': 'https://seller.kuajingmaihuo.com',
        'referer': 'https://seller.kuajingmaihuo.com/main/product/material',
        'sec-ch-ua': '"Google Chrome";v="117", "Not;A=Brand";v="8", "Chromium";v="117"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
        'sec-fetch-dest': 'empty',
        'sec-fetch-mode': 'cors',
        'sec-fetch-site': 'same-origin',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36',
    }

    headers.update({
        'mallid': mall_id,
    })

    json_data = {
        'pageInfo': {
            'pageNo': page,
            'pageSize': 100,
        },
        'taskMergedStatus': task_merged_status,  # 1代表待更新   2代表更新中   3代表待发布  4代表待确认   5代表已完成
    }

    response = requests.post(
        'https://seller.kuajingmaihuo.com/marvel-gmp/api/phoenix/picture/page-query-task-agg',
        cookies=cookies,
        headers=headers,
        json=json_data,
    )
    result_json = response.json()

    if result_json.get("error_msg"):
        print(result_json)
        return False

    data_list = result_json.get("result").get("detailList")
    if not data_list:
        print(result_json)
        record_count(mall_id=mall_id, count=0, platform="temu_seller_picture_{}".format(task_merged_status),
                     sql_obj=sql_obj)
        return []

    total = result_json.get("result").get("total")
    page_all = math.ceil(total / json_data["pageInfo"]["pageSize"])
    record_count(mall_id=mall_id, count=total, platform="temu_seller_picture_{}".format(task_merged_status),
                 sql_obj=sql_obj)

    for i in range(len(data_list)):
        msg = data_list[i]
        spu = msg["productId"]
        taskList = msg["taskList"]
        # print(i, "-----", spu)
        for skc in taskList:
            skc_detail = {}
            productSkcId = skc["productSkcId"]
            if productSkcId:
                skc_detail.update({
                    "date": datetime.now().strftime('%Y-%m-%d %H:%M:%S').split(" ")[0],
                    "platform": "temu_seller_picture_{}".format(task_merged_status),
                    "store_code": mall_id,
                    "spu": spu,
                    "skc": productSkcId,
                    "task_merged_status": task_merged_status,
                    "task_status": map_picture_status(task_merged_status)
                })
                # print(skc_detail)
                if productSkcId not in skcs:
                    skcs.append(productSkcId)
                else:
                    print("已经存在", productSkcId)

                sku_all.append(skc_detail)

    if page < page_all:
        page += 1
        return temu_shop_picture_api(page=page, mall_id=mall_id, sku_all=sku_all, task_merged_status=task_merged_status,
                                     sql_obj=sql_obj)
    else:
        print("sku 总量：{}".format(len(sku_all)))
        print("{}-{}采集结束, 总共{}页".format(mall_id, task_merged_status, page_all))
        return sku_all


def temu_shop_picture_all(mall_id="4594954014482", sql_obj=None):
    """
    按五种状态执行
    :return:
    """
    picture_all = []
    for task_merged_status in range(1, 6):
        sku_all = temu_shop_picture_api(page=1, mall_id=mall_id, sku_all=[], task_merged_status=task_merged_status,
                                        sql_obj=sql_obj)
        if sku_all:
            picture_all.extend(sku_all)
        time.sleep(10)
    return picture_all


if __name__ == '__main__':
    # 1 temu 卖家端  # 商品管理 - 上新生命周期管理 - 全部
    temu_xmen_api(mall_id="634418209736233", page=1, sku_all=[])

    # 2 商品管理 - 图片更新任务 - 待更新&更新中&待发布&待确认&已完成
    # temu_shop_picture_api(mall_id="4594954014482", task_merged_status=5)

    # 3商品管理 - 图片更新任务 五种状态全部执行
    # temu_shop_picture_all(mall_id="634418212290849")
